<?php

namespace app\service;

use app\common\BaseService;
use app\model\HouseInOrder as HouseInOrderModel;
use app\model\HouseIn as HouseInModel;
use think\facade\Db;

class HouseInService extends BaseService
{
  public static function getInstance(): HouseInService
  {
    return parent::getInstance();
  }

  public static function getModel(): HouseInOrderModel
  {
    return HouseInOrderModel::getInstance();
  }
  public static function getDetailModel(): HouseInModel
  {
    return HouseInModel::getInstance();
  }

  /*
   * 通过condition获取HouseInOrder
   */
  public function getHouseInByCondition($conditions, $field = '*', $orderField = 'id', $orderSort = 'DESC') {
    $query = self::getModel()->field($field);
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $query = $query->where($field, $op, $value);
    }
    if ($orderField != 'id') {
      $query = $query->order($orderField, $orderSort);
      $query = $query->order('id', 'desc');
    } else {
      $query = $query->order($orderField, $orderSort);
    }
    $result = $query->select()->toArray();
    return $result;
  }

  /*
   * 连商品表goods查询house_in信息
   */
  public function getHouseInJoinGoods($conditions = [],  $order = ['h.id' => 'DESC']) {
//    $conditions[] = ['o.status', 0,'<>'];
    $conditions[] = ['h.status', 1,'='];
    $query = Db::name('house_in')
      ->alias('h')
      ->field('h.*, o.process, o.house_in_number, o.supplier, o.comment as message, o.process, o.house_in_time, o.default_time, g.category_id, g.name, g.sellable, g.unit, g.unit_in, g.price_in as default_price, c.category_name')
      ->join('house_in_order o', 'o.id = h.in_order_id', 'LEFT')
      ->join('goods g', 'g.id = h.goods_id', 'LEFT')
      ->join('category c', 'g.category_id = c.id', 'LEFT');
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $query = $query->where($field, $op, $value);
    }
    $query = $query->order($order);
    return $query->select()->toArray();
  }

  /*
   * 删除house_in信息
   */
  public static function deleteHouseIn($id) {
    // 获取入库详情
    $houseIn = self::getDetailModel()
      ->where('id', '=', $id)
      ->find()
      ->toArray();
    // 获取house表实时数据
    $house = HouseService::getInstance()->getHouseJoinGoods([['goods_id', $houseIn['goods_id'], '=']]);
    $house = isset($house[0]) ? $house[0] : [];
    $newCost = $house['count'] - $houseIn['count'];
    if ($newCost < 0) {
      return ['status' => false, 'msg' => '库存不足'];
    }
    // 更新house表
    $updateHouse = [
      'count' => $house['count'] - $houseIn['count'],
      'total_amount' => round($house['total_amount'] - $houseIn['total_amount'], 2),
      'price' => ($house['count'] - $houseIn['count']) ? round(($house['total_amount'] - $houseIn['total_amount'])/($house['count'] - $houseIn['count']), 2) : 0,
      'last_update_time' => date('Y-m-d')
    ];
    self::getDetailModel()->startTrans();
    try {
      // 更新house表
      if ($updateHouse) {
        $res1 = HouseService::getModel()
          ->where('id', '=', $house['id'])
          ->save($updateHouse);
        if ($res1 === false) {
          throw new \Exception('更新house失败');
        }
      }
      // 更新house_in表
      $res2 = self::getDetailModel()
        ->where('id', '=', $id)
        ->save(['status' => 0, 'last_update_time' => date('Y-m-d')]);
      if ($res2 === false) {
        throw new \Exception('更新house_in失败');
      }
      self::getDetailModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getDetailModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }

  /*
   * 删除house_in_order信息
   */
  public static function deleteHouseInOrder($oid) {
    // 修改house
    $updateHouse = [];
    // 修改house_in 和 house_in_order
    $updateHouseIn = [
      'status' => 0,
      'last_update_time' => date('Y-m-d H:i:s')
    ];
    $orderList = self::getInstance()->getHouseInJoinGoods([['o.id', $oid, '='], ['o.status', 0,'<>']]);
    // 获取house表实时数据
    $houseList = HouseService::getModel()->select()->toArray();
    $houseList = array_column($houseList, null, 'goods_id');
    foreach ($orderList as $value) {
      $house = $houseList[$value['goods_id']];
      if ($house['count'] < $value['count']) {
        return ['status' => false, 'msg' => '库存不足'];
      }
      // 更新house表
      $updateHouse[] = [
        'id' => $house['id'],
        'count' => $house['count'] - $value['count'],
        'total_amount' => round($house['total_amount'] - $value['total_amount'], 2),
        'price' => ($house['count'] - $value['count']) ? round(($house['total_amount'] - $value['total_amount'])/($house['count'] - $value['count']), 2) : 0,
        'last_update_time' => date('Y-m-d')
      ];
    }
    self::getDetailModel()->startTrans();
    try {
      // 更新house表
      if ($updateHouse) {
        $res1 = HouseService::getModel()
          ->saveAll($updateHouse);
        if ($res1 === false) {
          throw new \Exception('更新house失败');
        }
      }
      // 更新house_in_order
      $res2 = HouseInService::getModel()
        ->where('id', '=', $oid)
        ->save($updateHouseIn);
      if ($res2 === false) {
        throw new \Exception('更新house_in_order失败');
      }
      // 更新house_in
      $res3 = HouseInService::getDetailModel()
        ->where('in_order_id', '=', $oid)
        ->save($updateHouseIn);
      if ($res3 === false) {
        throw new \Exception('更新house_in失败');
      }
      self::getDetailModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getDetailModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }

  /**
   * 修改house_in数据
   */
  public static function updateHouseInOrder($oid, $supplier, $default_time, $data) {
    // 获取order数据
    $houseOrder = self::getModel()
      ->find($oid)
      ->toArray();
    $houseOrderUpdate = [];
    if ($houseOrder['supplier'] !== $supplier || $houseOrder['default_time'] !== $default_time) {
      $houseOrderUpdate = [
        'supplier' => $supplier,
        'status' => 2,
        'comment' => '',
        'default_time' => $default_time
      ];
    }
    // 新增到house_in
    $insertHouseIn = [];
    // 获取商品表数据
    $goodsList = GoodsService::getInstance()->getGoodsByCondition([['process', $houseOrder['process'], '='], ['status', 1, '=']]);
    $goodsList = array_column($goodsList, null, 'id');
    // 获取house_in数据
    foreach ($data as $value) {
      $goodsId = $value['goods_id'];
      // 入库的数量
      $count = $value['count_in'] * $goodsList[$goodsId]['conversion'];
      // 入库总价
      $totalAmount = $value['count_in'] * $value['price_in'];
      $insertHouseIn[] = [
        'goods_id' => $goodsId,
        'in_order_id' => $oid,
        'price_in' => $value['price_in'],
        'count_in' => $value['count_in'],
        'count' => $count,
        'conversion' => $value['conversion'] ? $value['conversion'] : 1,
        'total_amount' => round($totalAmount, 2),
        'price' => round($totalAmount / $count, 2),
        'comment' => $value['comment'],
        'status' => 1,
        'insert_time' => date('Y-m-d H:i:s'),
        'last_update_time' => date('Y-m-d H:i:s')
      ];
    }
    self::getModel()->startTrans();
    try {
      // 更新house_in_order
      if ($houseOrderUpdate) {
        $res1 = HouseInService::getModel()
          ->where('id', '=', $oid)
          ->save($houseOrderUpdate);
        if ($res1 === false) {
          throw new \Exception('更新house_in_order失败');
        }
      }
      if ($insertHouseIn) {
        // 删除house_in
        $res2 = HouseInService::getDetailModel()
          ->where('in_order_id', '=', $oid)
          ->delete();
        if ($res2 === false) {
          throw new \Exception('删除house_in失败');
        }

        // 新增house_in
        $res3 = HouseInService::getDetailModel()->insertAll($insertHouseIn);
        if ($res3 === false) {
          throw new \Exception('新增house_in失败');
        }
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }

  /**
   * 审核采购单
   */
  public static function checkHouseInOrder($orderId, $check, $comment) {
    $insertHouse = [];
    $updateHouse = [];
    if ($check) {
      // 获取商品表数据
      $goodsList = GoodsService::getInstance()->getGoodsByCondition([['process', 0, '='], ['status', 1, '=']]);
      $goodsList = array_column($goodsList, null, 'id');
      // 获取house表数据
      $houseList = HouseService::getHouseJoinGoods([['h.process', 0, '='], ['h.status', 1, '=']]);
      $houseList = array_column($houseList, null, 'goods_id');
      // 获取详情
      $updateHouseOrder = [
        'status' => 1,
        'house_in_time' => date('Y-m-d'),
        'last_update_time' => date('Y-m-d H:i:s')
      ];
      $houseIn = self::getDetailModel()
        ->where('in_order_id', '=', $orderId)
        ->select()
        ->toArray();
      foreach ($houseIn as $value) {
        $goodsId = $value['goods_id'];
        $conversion = isset($value['conversion']) ? $value['conversion'] : $goodsList[$goodsId]['conversion'];
        // 入库的数量
        $count = $value['count_in'] * $conversion;
        // 入库总价
        $totalAmount = $value['count_in'] * $value['price_in'];
        if (isset($houseList[$goodsId]) && $houseList[$goodsId]) {
          $house = $houseList[$goodsId];
          $updateHouse[$house['id']] = [
            'count' => $house['count'] + $count,
            'total_amount' => round($house['total_amount'] + $totalAmount, 2),
            'price' => round(($house['total_amount'] + $totalAmount) / ($house['count'] + $count), 2),
            'last_update_time' => date('Y-m-d')
          ];
        } else {
          $insertHouse[] = [
            'goods_id' => $goodsId,
            'count' => $count,
            'total_amount' => round($totalAmount, 2),
            'price' => round($totalAmount / $count, 2),
            'process' => 0,
            'status' => 1,
            'insert_time' => date('Y-m-d H:i:s'),
            'last_update_time' => date('Y-m-d H:i:s')
          ];
        }
      }
    } else {
      $updateHouseOrder = [
        'status' => 3,
        'comment' => $comment,
        'last_update_time' => date('Y-m-d H:i:s')
      ];
    }
    self::getModel()->startTrans();
    try {
      // 新增house
      if ($insertHouse) {
        $res1 = HouseService::getModel()->insertAll($insertHouse);
        if ($res1 === false) {
          throw new \Exception('新增house失败');
        }
      }
      // 更新house
      if ($updateHouse) {
        foreach ($updateHouse as $key => $value) {
          $res2 = HouseService::getModel()
            ->where('id', '=', $key)
            ->save($value);
          if ($res2 === false) {
            throw new \Exception('更新house失败');
          }
        }
      }
      if ($updateHouseOrder) {
        // 更新house_in_order
        $res3 = self::getModel()
          ->where('id', '=', $orderId)
          ->save($updateHouseOrder);
        if ($res3 === false) {
          throw new \Exception('新增house_in_order失败');
        }
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }


}